#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2000'010;
const ll mod = 1000'000'000LL;
vector<int> adj[N];
int mx = 0, a[N], in[N], out[N], rs[N], cs = 0;
map<int, int> cnt[2];
map<pair<int,int>,int> id;
set<int> s[2];
void add(int x, int p)
{
cnt[p][a[x]]++;
if(cnt[p][a[x]] == 2)
s[p].insert(-a[x]);
}
void rmv(int x, int p)
{
if(cnt[p][a[x]] == 2)
s[p].erase(-a[x]);
cnt[p][a[x]]--;
}
int getans(int x)
{
if(s[x].empty())
return 0;
return -*s[x].begin();
}
void dfs(int u, int p, int bad)
{
in[u]=cs++;
if(u == bad)
bad = -1;
if(bad != -1){
add(u, 0);
}
else
add(u, 1);
for(int v: adj[u])
{
if(v == p)
continue;
dfs(v, u, bad);
}
out[u]=cs++;
}
void swp(int u, int p)
{
// cout << u << '\n';
rmv(u, 0);
add(u, 1);
for(int v: adj[u])
{
if(v == p)
continue;
swp(v, u);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for(int i = 0; i < n-1; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
id[{u,v}] = id[{v,u}] = i;
rs[i] = -1;
}
for(int i = 1; i <= n; i++)
{
cin >> a[i];
cnt[0][a[i]]++;
}
for(int i = 1; i <= n; i++)
{
if(cnt[0][a[i]] > 1)
mx = max(mx, a[i]);
}
if(cnt[0][mx] > 2 || mx == 0)
{
for(int i = 0; i < n-1; i++)
cout << mx << '\n';
return 0;
}
cnt[0].clear();
int u, v;
u = -1;
for(int i = 1; i <= n; i++)
{
if(a[i] == mx)
{
if(u == -1)
u = i;
else
v = i;
}
}
// cout << u << ' ' << v << '\n';
dfs(u, u, v);
int x = v, px = v;
while(x != u)
{
for(int at: adj[x])
{
if(in[at] <= in[v] && out[v] <= out[at] && px != at)
{
px = x;
x = at;
break;
}
}
rs[id[{px,x}]] = max(getans(1),getans(0));
// cout << x << ' ' << px << " " << rs[id[{px,x}]]<< " << \n";
for(int at: adj[x])
{
if(!(in[at]<= in[v] && out[v] <= out[at]))
{
swp(at, x);
// break;
}
}
rmv(x,0);
add(x,1);
}
for(int i = 0; i < n-1; i++)
{
if(rs[i] == -1)
cout << mx << '\n';
else
cout << rs[i] << '\n';
}
return 0;
}
785. Is Graph Bipartite | 90. Subsets II |
1560A - Dislike of Threes | 36. Valid Sudoku |
557. Reverse Words in a String III | 566. Reshape the Matrix |
167. Two Sum II - Input array is sorted | 387. First Unique Character in a String |
383. Ransom Note | 242. Valid Anagram |
141. Linked List Cycle | 21. Merge Two Sorted Lists |
203. Remove Linked List Elements | 733. Flood Fill |
206. Reverse Linked List | 83. Remove Duplicates from Sorted List |
116. Populating Next Right Pointers in Each Node | 145. Binary Tree Postorder Traversal |
94. Binary Tree Inorder Traversal | 101. Symmetric Tree |
77. Combinations | 46. Permutations |
226. Invert Binary Tree | 112. Path Sum |
1556A - A Variety of Operations | 136. Single Number |
169. Majority Element | 119. Pascal's Triangle II |
409. Longest Palindrome | 1574A - Regular Bracket Sequences |